package com.qf.smsplatfrom.sucurity;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatfrom.dto.R;
import com.qf.smsplatfrom.mapper.MenuMapper;
import com.qf.smsplatfrom.mapper.RoleMenuMapper;
import com.qf.smsplatfrom.mapper.UserRoleMapper;
import com.qf.smsplatfrom.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import sun.plugin.liveconnect.SecurityContextHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private UserRoleMapper userRoleMapper;
    private RoleMenuMapper roleMenuMapper;
    private MenuMapper menuMapper;
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Autowired
    public void setRoleMenuMapper(RoleMenuMapper roleMenuMapper) {
        this.roleMenuMapper = roleMenuMapper;
    }

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authentication);
        Object principal = authentication.getPrincipal();//获取当前登录的该用户的权限
        long id = ((MyAuthUser) principal).getId();//获取到当前登录用户的id
        //获取到当前用户的所有的权限
        //根据用户 id 获取到所有的角色的 id
        List<TUserRole> userRoleList = userRoleMapper.showUserRoleByUid(id);
        //根据角色的 id 获取到所有的地址的 id
        List<Long> roleIds = new ArrayList<>();
        userRoleList.forEach(tUserRole -> {
            long roleId = tUserRole.getRoleId();
            roleIds.add(roleId);
        });
        List<Long> menuIds = new ArrayList<>();
        roleIds.forEach(role -> {
            List<TRoleMenu> menus = roleMenuMapper.showTRoleMenuById(role);
            menus.forEach(tRoleMenu -> {
                long menuId = tRoleMenu.getMenuId();
                menuIds.add(menuId);
            });
        });
        //根据 地址的 id 获取到所有的地址的信息
        List<TMenu> tMenuList = new ArrayList<>();
        menuIds.forEach(menu -> {
            List<TMenu> menuList = menuMapper.findAllMenusByUserId(menu);
            tMenuList.addAll(menuList);
        });

        List<SimpleGrantedAuthority> simpleGrantedAuthorities = tMenuList.stream().filter(tMenu -> !ObjectUtils.isEmpty(tMenu.getPerms()))//只保留有权限的数据
                .map(TMenu::getPerms)//将当前集合中的是按照我们要求的数据通过 getPerms转成字符串集合
                .map(SimpleGrantedAuthority::new)//将字符串集合遍历，通过new SimpleGrantedAuthority将权限设置进去作为转换对象
                .collect(Collectors.toList());

        //重新设置权限的认证信息
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal,authentication.getCredentials(),simpleGrantedAuthorities));

        R r = R.setOk();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(r));


    }
}
